//
//  HomeViewController.m
//  jingjing2.0
//
//  Created by apple on 16/4/27.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HomeViewController.h"
#import "LocationCityViewController.h"
#import "WelfareListCell.h"
#import "ProListCell.h"
#import "BannerListCell.h"
#import "AboutListCell.h"
#import "HomeData.h"
#import "HomeData2.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import "JianXiViewController.h"
#import "YueXiViewController.h"
@interface HomeViewController ()<AMapLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (nonatomic,strong)AMapLocationManager * locationManager;
@property(nonatomic,strong)UIButton *locationBtn;
@property(nonatomic,strong)NSArray *cityArr;
@property(nonatomic,strong)LocationCityViewController *locationCity;
@property(nonatomic,strong)UIPageControl *pageCtl;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor=[UIColor whiteColor];
   
    /* 如果定位成功并且当前定位城市已开通则直接显示城市
     * 如果定位成功但是当前定位城市没有开通则默认为大连
     * 如果定位不成功就进入选择城市列表
     */
   
    [self getExitedCity];//获取已经开通的城市
 //   [self getUserLocation];//定位当前城市
    [self setUpTableView];
    [self setUpNav];
    [self getHomeData];
  
    
}

#pragma mark--高德定位
-(void)getUserLocation
{
      MBProgressHUD *hud=[MBProgressHUD showMessage:@"正在确定您的位置,请稍后..."];
        [AMapLocationServices sharedServices].apiKey = APIKEY;
        
        self.locationManager = [[AMapLocationManager alloc] init];
        
        // 带逆地理信息的一次定位（返回坐标和地址信息）
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        //   定位超时时间，可修改，最小2s
        self.locationManager.locationTimeout = 3;
        //   逆地理请求超时时间，可修改，最小2s
        self.locationManager.reGeocodeTimeout = 3;
        
        // 带逆地理（返回坐标和地址信息）
        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            [hud removeFromSuperview];
            if (error)
            {
                NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                [ZMTool showAlertWithDifferentVersioninWhichViewController:self withTitle:@"提示" andMessage:@"定位失败！请切换到已开通的城市！" andSureTitle:@"好" andCancleTitle:nil isDelegate:YES andSureBlock:^(UIAlertAction *action)
                {
                    
                    [self pushToLocationChooseViewControllerWithCity:@"定位失败"];
                    [self saveDataWithCityName:@"大连市"];
                    NSUserDefaults *data=[NSUserDefaults standardUserDefaults];
                    [data setObject:@"大连市" forKey:@"CurrentCity"];
                    [data synchronize];
                } andCancleBlock:nil];
            }
            
            else if (regeocode)
            {
                NSLog(@"reGeocode:%@", regeocode.province);
                   //定位成功后判断当前城市有没有开通
                if (self.cityArr.count>0) {
                    NSMutableArray *cities=[NSMutableArray array];
                    [self.cityArr enumerateObjectsUsingBlock:^(NSDictionary * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [cities addObject:[obj[@"CityName"]stringByRemovingPercentEncoding]];
                        
                    }];
                    if (regeocode.province) {
                        if ([cities containsObject:regeocode.province])
                        {
                            //如果定位成功并已开通且则直接显示位置
                            [self.locationBtn setTitle:regeocode.province forState:UIControlStateNormal];
                            [self saveDataWithCityName:regeocode.province];
                            NSUserDefaults *data=[NSUserDefaults standardUserDefaults];
                            [data setObject:regeocode.province forKey:@"CurrentCity"];
                            [data synchronize];
                            
                        }else
                        {
                            //如果定位成功但并没有开通则提示是否切换
                            [ZMTool showAlertWithDifferentVersioninWhichViewController:self withTitle:nil andMessage:@"您当前定位的城市尚未开通，是否切换开通的城市" andSureTitle:@"取消" andCancleTitle:@"切换" isDelegate:YES andSureBlock:^(UIAlertAction *action) {
                                
                                [self pushToLocationChooseViewControllerWithCity:regeocode.province];
                                
                            } andCancleBlock:nil];
                        }

                    }else
                    {
                        [MBProgressHUD showError:@"定位失败，无法获取当前城市"];
                    }
                }else
                {
                    [MBProgressHUD showError:@"定位失败，无法获取当前城市"];
                }
                
            }
        }];
 
}

#pragma mark--设置导航条
-(void)setUpNav
{
    self.view.backgroundColor=[UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets=NO;
    UIImageView *imageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"home_title"]];

    self.navigationItem.titleView = imageView;
    
    // 右边指示图标
    UIBarButtonItem *right=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"down_icon_blue_new"] style:UIBarButtonItemStylePlain target:self action:@selector(showMapLocation)];
    self.navigationItem.rightBarButtonItem=right;
    
    //显示定位信息
    _locationBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-100, 0, 80, 44)];
    
    [_locationBtn setTitle:@"大连市" forState:UIControlStateNormal];
    
    [_locationBtn setTitleColor:BLUECOLOR forState:UIControlStateNormal];
    
    _locationBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _locationBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    
    [_locationBtn addTarget:self action:@selector(showMapLocation) forControlEvents:UIControlEventTouchUpInside];
    
    [self.navigationController.navigationBar addSubview:_locationBtn];
 
}
#pragma mark--工具方法
//进入定位界面
-(void)showMapLocation
{
    [self pushToLocationChooseViewControllerWithCity:[_locationBtn titleForState:UIControlStateNormal]];
}
//显示定位按钮
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self beginRefreshing];
    self.locationBtn.hidden=NO;
    self.hidesBottomBarWhenPushed=NO;
   
}
//隐藏
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.locationBtn.hidden=YES;
    
}
//进入城市选择
-(void)pushToLocationChooseViewControllerWithCity:(NSString *)city
{
    if (!_locationCity) {
        _locationCity=[[LocationCityViewController alloc]init];
    }
    _locationCity.cityArr=self.cityArr;
    _locationCity.currentCity=city;
    typeof(self) weakSelf=self;
    _locationCity.passCityBlock=^(NSString *cityName,NSString *cityCode)
    {
        [weakSelf.locationBtn setTitle:cityName forState:UIControlStateNormal];
    };
    [self pushToViewControllerWith:_locationCity];
}

#pragma mark--获取开通的城市

-(void)getExitedCity
{

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *timeStamp=[GeneralTool gettimestamp];
    
    NSDictionary *signDic=@{@"Timestamp":timeStamp};
    
    NSString *sign=[GeneralTool GetSin:signDic];
    
    NSString *urlString=[NSString stringWithFormat:@"Common/OpenCity/%@/%@",timeStamp,sign];
    
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if ([responses[@"IsSuccess"]intValue]==1) {
           
            self.cityArr=responses[@"ReturnObject"];
        }else
        {
            [MBProgressHUD showError:@"获取城市失败"];
        }
        
    }];
}
#pragma mark--保存cityCode到本地
-(void)saveDataWithCityName:(NSString *)cityName
{
    
    for (NSDictionary *dic in self.cityArr) {
        //如果当前定位城市存在于开通城市列表中，根据当前城市获取当前城市的cityCode
        NSString *str=[dic[@"CityName"] stringByRemovingPercentEncoding];
        if ([str isEqualToString:cityName]) {
            NSString *cityCode=dic[@"CityCode"];
            //将cityCode保存到本地
            NSUserDefaults *data=[NSUserDefaults standardUserDefaults];
            [data setObject:cityCode forKey:@"cityCode"];
            [data synchronize];
        }
    }
}

#pragma mark--获取首页数据
-(void)getHomeData
{
     NSString *timestamp=[GeneralTool gettimestamp];
        if (!GETUSERCODE) {
        return;
    }
        NSDictionary *dic=@{@"UserCode":GETUSERCODE,
                            @"VerNumber":VERNUMBER,
                            @"CityCode":GETCITYCODE,
                            @"SourceID":@"3",
                            @"Timestamp":timestamp};
        NSString *sign=[GeneralTool GetSin:dic];
        NSString *urlString=[NSString stringWithFormat:@"Common/HomeInfo/%@/%@/%@/%@/%@/%@",GETUSERCODE,VERNUMBER,GETCITYCODE,@"3",timestamp,sign];
        [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error) {
         
            
            if (error) {
                
                [MBProgressHUD showError:@"刷新失败，请检查网络"];
               
            }else
            {
                if ([responses[@"IsSuccess"]intValue]==1) {
            
                    NSArray * keys = @[@"BannerList",@"ProList",@"WelfareList",@"AboutList"];
                    
                    NSDictionary * bigDict = [responses objectForKey:@"ReturnObject"];
                    if (bigDict!=[NSNull null]) {
                        for (int i = 0 ; i < keys.count ; i++)
                        {
                            NSArray * resultArray = [bigDict objectForKey:keys[i]];
                            NSMutableArray *Arr=[NSMutableArray array];
                            for (NSDictionary *dic in resultArray)
                            {
                                if ([keys[i] isEqualToString:@"BannerList"]) {
                                    HomeData2 *data2=[[HomeData2 alloc]initWithDic:dic];
                                    [Arr addObject:data2];
                                }else
                                {
                                    HomeData *data=[[HomeData alloc]initWithDic:dic];
                                    [Arr addObject:data];
                                }
                            }
                            [self.dataSource addObject:Arr];
                        }

                    }
                    
                }else
                {
                    NSString *returnString=[responses[@"ReturnString"] stringByRemovingPercentEncoding];
                    [MBProgressHUD showError:returnString];
                }
                [_tableView reloadData];
            }
        }];
         [_tableView.mj_header endRefreshing];
}

#pragma mark--表
-(void)setUpTableView
{
    //初始化数组
    if (!_dataSource)
    {
        _dataSource = [NSMutableArray array];
    }
    //初始化表
    //创建表
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64-50) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1];
        [_tableView registerNib:[UINib nibWithNibName:@"WelfareListCell" bundle:nil] forCellReuseIdentifier:@"WelfareList"];
        [_tableView registerNib:[UINib nibWithNibName:@"ProListCell" bundle:nil] forCellReuseIdentifier:@"ProList"];
        [_tableView registerNib:[UINib nibWithNibName:@"BannerListCell" bundle:nil] forCellReuseIdentifier:@"BannerList"];
        [_tableView registerNib:[UINib nibWithNibName:@"AboutListCell" bundle:nil] forCellReuseIdentifier:@"AboutList"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
#pragma mark--刷新
-(void)beginRefreshing
{
    [_tableView.mj_header beginRefreshing];

}
-(void)refreshTheTableView
{
    [self.dataSource removeAllObjects];
    [_tableView reloadData];
     [self getHomeData];
   
}
#pragma mark--表代理方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataSource.count!=0)
    {
        if (section==1)
        {
           return [self.dataSource[section] count];
        }else if(section==2)
        {
           return [self.dataSource[section] count]/2;
        }else
        {
            return 1;
        }
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0 ) {
        return 150;
    } else if (indexPath.section==1)
    {
        return 80;
    }
    else if (indexPath.section==2)
    {
        return 80;
    }else
    {
        return 58;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==3 || section==2) {
        return 1;
    }
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==1 || section==3) {
        return 1;
    }
    return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *arr=self.dataSource[indexPath.section];
        if (indexPath.section==0) {
            BannerListCell *banner=[tableView dequeueReusableCellWithIdentifier:@"BannerList" forIndexPath:indexPath];
            //滑动视图
            banner.selectionStyle=UITableViewCellSelectionStyleNone;
            [self addCornerRadiusTo:banner.scrollView];
            banner.scrollView.delegate=self;
            banner.scrollView.contentSize=CGSizeMake(banner.scrollView.frame.size.width*arr.count, banner.frame.size.height);
            //创建图片和分页控件
            [self setUpImageWithArray:arr andSuperView:banner.scrollView];
            [self setUpPageControlWithSuperView:banner.contentView AndNumber:arr.count];
        
            return banner;
        }else if (indexPath.section==1)
        {
            ProListCell *pro=[tableView dequeueReusableCellWithIdentifier:@"ProList" forIndexPath:indexPath];
           
            pro.selectionStyle=UITableViewCellSelectionStyleNone;
            [self addCornerRadiusTo:pro.bgView];
            HomeData *data=arr[indexPath.row];
            pro.tag=data.CategoryID;
            pro.name.text=[data.CategoryName stringByRemovingPercentEncoding];
            pro.price.text=[data.Intro stringByRemovingPercentEncoding];
            pro.remark.text=[data.Remark stringByRemovingPercentEncoding];
            [pro.image sd_setImageWithURL:[NSURL URLWithString:data.IconUrl]];
            return pro;
        }else if (indexPath.section==2)
        {
            WelfareListCell *welfare=[tableView dequeueReusableCellWithIdentifier:@"WelfareList" forIndexPath:indexPath];
            welfare.delegate=self;
            welfare.selectionStyle=UITableViewCellSelectionStyleNone;
              welfare.image2.image=nil;
             welfare.image1.image=nil;
            [self addCornerRadiusTo:welfare.bgView1];
            [self addCornerRadiusTo:welfare.bgView2];
            
            NSInteger index = 0;
            if (indexPath.row == 1)
            {
                index = 2;
            }
            if (index+1 > arr.count - 1)
            {
                return NULL;
            }
            HomeData * data1 = arr[index];
            HomeData * data2 = arr[1+index];

            welfare.name1.text=[data1.CategoryName stringByRemovingPercentEncoding];
            welfare.button1.title=data1.CategoryName;
            welfare.button1.tag=data1.CategoryID;
            welfare.remark1.text=[data1.Remark stringByRemovingPercentEncoding];
            [welfare.image1 sd_setImageWithURL:[NSURL URLWithString:data1.IconUrl]];
        
            welfare.name2.text=[data2.CategoryName stringByRemovingPercentEncoding];
            welfare.button2.title=data2.CategoryName;
            welfare.button2.tag=data2.CategoryID;
            welfare.remark2.text=[data2.Remark stringByRemovingPercentEncoding];
            [welfare.image2 sd_setImageWithURL:[NSURL URLWithString:data2.IconUrl]];

            
            return welfare;
        }else
        {
            AboutListCell *about=[tableView dequeueReusableCellWithIdentifier:@"AboutList" forIndexPath:indexPath];
            about.selectionStyle=UITableViewCellSelectionStyleNone;
            for (int a=0; a<arr.count; a++)
            {
                HomeData *data=arr[a];
                if ((a+1)%2==0) {
                  [about.btn2 setTitle:data.CategoryName forState:UIControlStateNormal];
                    about.btn2.pageUrl=data.NextPageUrl;
                    about.btn2.IsStatic=data.UrlType;
                    [about.btn2 addTarget:self action:@selector(clickOnBtn:) forControlEvents:UIControlEventTouchUpInside];
                  [self addCornerRadiusTo:about.btn2];
                }else if ((a+1)%3==0)
                {
                  [about.btn3 setTitle:data.CategoryName forState:UIControlStateNormal];
                     about.btn3.pageUrl=data.NextPageUrl;
                     about.btn3.IsStatic=data.UrlType;
                    [about.btn3 addTarget:self action:@selector(clickOnBtn:) forControlEvents:UIControlEventTouchUpInside];
                   [self addCornerRadiusTo:about.btn3];
                }else
                {
                  [about.btn1 setTitle:data.CategoryName forState:UIControlStateNormal];
                     about.btn1.pageUrl=data.NextPageUrl;
                     about.btn1.IsStatic=data.UrlType;
                    [about.btn1 addTarget:self action:@selector(clickOnBtn:) forControlEvents:UIControlEventTouchUpInside];
                  [self addCornerRadiusTo:about.btn1];
                  }
        }
            
            return about;
    }
   
}
-(void)clickOnBtn:(CustomButton *)btn
{
    NSString *pageUrl=nil;
    
    if (btn.IsStatic==1) {
        
        pageUrl=btn.pageUrl;
        
    }else
    {
        pageUrl=QUESTIONLIST;
    }
    WebViewController *web=[[WebViewController alloc]init];
    web.title=[btn titleForState:UIControlStateNormal];
    web.pageUrl=pageUrl;
    web.hidesBottomBarWhenPushed=YES;
    [self pushToViewControllerWith:web];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0 || indexPath.section==3) {
        return;
    }else if (indexPath.section==1)
    {
        NSMutableArray *arr=self.dataSource[indexPath.section];
        HomeData *data=arr[indexPath.row];
        if ([[data.CategoryName stringByRemovingPercentEncoding] isEqualToString:@"包月洗"])
        {
            //包月洗
            YueXiViewController *yueXi=[[YueXiViewController alloc]init];
            yueXi.hidesBottomBarWhenPushed=YES;
            [self.navigationController pushViewController:yueXi animated:YES];
        }else
        {
            //件洗／洗衣／洗鞋
            ProListCell *pro=[_tableView cellForRowAtIndexPath:indexPath];
            JianXiViewController *JianXi=[[JianXiViewController alloc]init];
            JianXi.categoryID=pro.tag;
            JianXi.hidesBottomBarWhenPushed=YES;
            [self pushToViewControllerWith:JianXi];
        }
    }else if (indexPath.section==2)
    {
        
    }
}
#pragma mark--滚动视图
-(void)setUpImageWithArray:(NSArray *)arr andSuperView:(UIScrollView *)view
{
    CGSize size=view.frame.size;
    [[view viewWithTag:999]removeFromSuperview];
    for (int i =0; i<arr.count; i++) {
        HomeData2 *data2=arr[i];
         CustomButton *imageBtn=[[CustomButton alloc]initWithFrame:CGRectMake(i*size.width, 0, size.width, size.height)];
            imageBtn.imageView.contentMode=UIViewContentModeCenter;
            imageBtn.pageUrl=data2.PageUrl;
            imageBtn.IsStatic=data2.IsStatic;
            imageBtn.title=[data2.Title stringByRemovingPercentEncoding];
            [imageBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:data2.appIndexImage] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageRetryFailed|SDWebImageRefreshCached];
            imageBtn.tag=999;
            [imageBtn addTarget:self action:@selector(clickOnScroll:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:imageBtn];
        }
    [view setContentOffset:CGPointMake(0, 0)];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageCtl.currentPage=scrollView.contentOffset.x/(self.tableView.frame.size.width-20);
}


-(void)clickOnScroll:(CustomButton *)btn
{
    if(btn.IsStatic==1)
    {
        WebViewController *web=[[WebViewController alloc]init];
        web.title=btn.title;
        web.pageUrl=btn.pageUrl;
        [self pushToViewControllerWith:web];
        
    }else
    {
        //跳进邀请好友界面
    }
}

#pragma mark--创建分页小圆点
-(void)setUpPageControlWithSuperView:(UIView *)view AndNumber:(NSInteger)number
{
    CGSize size=view.frame.size;
    [[view viewWithTag:9999]removeFromSuperview];
     _pageCtl=[[UIPageControl alloc]initWithFrame:CGRectMake(0, size.height-30, size.width, 10)];
    _pageCtl.numberOfPages=number;
    _pageCtl.currentPage=0;
    _pageCtl.tag=9999;
    _pageCtl.currentPageIndicatorTintColor=BLUECOLOR;
    _pageCtl.pageIndicatorTintColor=GRAYCOLOR;
    _pageCtl.enabled=NO;
    [view addSubview:_pageCtl];
 
}

//圆角半径和阴影
-(void)addCornerRadiusTo:(UIView *)view
{
    view.layer.cornerRadius=3;
    view.layer.shadowColor = [UIColor lightGrayColor].CGColor;//shadowColor阴影颜色
    view.layer.shadowOffset = CGSizeMake(2,2);//shadowOffset阴影偏移,x向右偏移2，y向下偏移2，默认(0, -3),这个跟shadowRadius配合使用
    view.layer.shadowOpacity = 1;//阴影透明度，默认0
    view.layer.shadowRadius = 2;//阴影半径，默认3

}

#pragma mark--隐藏底部视图
-(void)pushToViewControllerWith:(UIViewController *)controller
{
    [self.navigationController pushViewController:controller animated:YES];
}

@end
